package com.gitee.interceptor;

import cn.hutool.core.util.StrUtil;
import com.gitee.enums.ResponseEnum;
import com.gitee.exception.LoginException;
import com.gitee.exception.UserException;
import com.gitee.pojo.User;
import com.gitee.service.IUserService;
import com.gitee.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private IUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        // 判断token是否存在
        if (StrUtil.isBlank(token)) {
            throw new LoginException(ResponseEnum.NO_LOGIN);
        }
        // 获取载荷
        Claims claims = JwtUtil.checkJWT(token);
        // 判断token是否过期
        long expireTime = claims.getExpiration().getTime();
        if (new Date().getTime() > expireTime) {
            throw new LoginException(ResponseEnum.NO_LOGIN);
        }
        // 判断用户状态
        Integer userId = (Integer)claims.get("userId");
        if (userId == null) {
            throw new LoginException(ResponseEnum.NO_LOGIN);
        }
        User user = userService.getById(userId);
        if (user == null || !user.getEnabled()) {
            throw new UserException(ResponseEnum.NO_ACCEPT);
        }
        return true;
    }
}
